package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.JSONResult;
import cn.wolfcode.crm.util.PageResult;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;

    @RequestMapping("view")
    @RequiresPermissions(value = {"employee:view", "员工界面"}, logical = Logical.OR)
    public String employee(QueryObject qo) {
        return "employee";
    }

    @RequestMapping("query")
    @ResponseBody
    public PageResult query(EmployeeQueryObject qo) {
        return employeeService.query(qo);
    }

    @RequestMapping("list")
    @ResponseBody
    public Object list() {
        return employeeService.selectAll();
    }

    @RequestMapping("validateName")
    @ResponseBody
    public Boolean validateName(String username, Long id) {
        return employeeService.validateName(username, id);
    }

    /**
     * 导出文件操作
     */
    @RequestMapping("exportXls")
    public void exportXls(HttpServletResponse resp, EmployeeQueryObject qo) throws IOException {
        //设置下载响应头
        resp.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        //1.创建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象（创建工作薄）
        HSSFSheet sheet = wb.createSheet("employee");

        //把高级查询加入查询员工列表中
        List<Employee> employees = (List<Employee>) employeeService.query(qo).getRows();

        //创建第一行
        Row row = sheet.createRow(0);
        //设置标题
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("真实姓名");
        row.createCell(2).setCellValue("电话");
        row.createCell(3).setCellValue("邮箱");
        row.createCell(4).setCellValue("部门名称");
        row.createCell(5).setCellValue("入职时间");
        for (int i = 0; i < employees.size(); i++) {
            //从第二行开始创建行
            row = sheet.createRow(i + 1);
            Employee employee = employees.get(i);
            //创建单元格
            row.createCell(0).setCellValue(employee.getUsername());
            row.createCell(1).setCellValue(employee.getRealname());
            row.createCell(2).setCellValue(employee.getTel());
            row.createCell(3).setCellValue(employee.getEmail());
            row.createCell(4).setCellValue(employee.getDept().getName());

            //设置输出日期的单元格格式为日期格式操作
            CreationHelper createHelper = wb.getCreationHelper();
            CellStyle cellStyle = wb.createCellStyle();
            //设置日期格式
            cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/M/dd"));
            Cell cell = row.createCell(5);
            cell.setCellValue(employee.getHireDate());
            //把格式设置进去
            cell.setCellStyle(cellStyle);
        }
        //输出到浏览器
        wb.write(resp.getOutputStream());
    }

    /**
     * 导入文件操作
     */
    @RequestMapping("importXls")
    @ResponseBody
    public JSONResult importXls(MultipartFile file) throws IOException {
        JSONResult result = new JSONResult();
        try {
            if (file != null && file.getSize() > 0) {
                //获取excel文件
                Workbook wb = new HSSFWorkbook(file.getInputStream());
                //获取工作薄
                Sheet sheet = wb.getSheet("employee");
                //获取最后一行 就是总行数
                int lastRowNum = sheet.getLastRowNum();
                for (int i = 1; i <= lastRowNum; i++) {
                    //获取每一行 excel表抬头是标题 所以索引是从1开始
                    Row row = sheet.getRow(i);
                    Employee employee = new Employee();
                    //新建部门对象
                    Department department = new Department();

                    //从上传进来的文件中设置数据
                    employee.setUsername(row.getCell(0).getStringCellValue());
                    employee.setRealname(row.getCell(1).getStringCellValue());
                    employee.setTel(row.getCell(2).getStringCellValue());
                    employee.setEmail(row.getCell(3).getStringCellValue());

                    //先判断当前的部门名称是否已经存在于部门表中
                    String deptName = row.getCell(4).getStringCellValue();
                    //查询当前传进来的部门名称 是否为null
                    Department depar = departmentService.selectByDepartmentName(deptName);
                    if (depar == null) {
                        //保存部门的操作 先插入到部门表 然后拿到部门表的id 并且整个部门插入到员工中
                        department.setName(deptName);
                        //保存到部门表中
                        departmentService.saveOrUpdate(department);
                        //查询出当前部门的id
                        Department dept = departmentService.selectByPrimaryKey(department.getId());
                        //然后再保存进员工表中
                        employee.setDept(dept);
                    } else {
                        //如果不为null 则把查询出来的部门直接保存到员工中
                        employee.setDept(depar);
                    }

                    CreationHelper createHelper = wb.getCreationHelper();
                    CellStyle cellStyle = wb.createCellStyle();
                    //设置日期格式
                    cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/MM/dd"));
                    Cell cell = row.getCell(5);
                    cell.setCellStyle(cellStyle);
                    Date date = cell.getDateCellValue();
                    //给员工对象设置日期
                    employee.setHireDate(date);
                    //并且get员工设置默认密码为1
                    employee.setPassword("1");
                    //设置上传的员工都默认不是管理员
                    employee.setAdmin(false);
                    //保存到数据库中
                    employeeService.saveOrUpdate(employee);
                }
            }
        } catch (IOException e) {
            result.remark("上传失败,请重新上传");
            e.printStackTrace();
        }
        //返回result
        return result;
    }

    @RequestMapping("saveOrUpdate")
    @RequiresPermissions(value = {"employee:saveOrUpdate", "员工新增/更新"}, logical = Logical.OR)
    @ResponseBody
    public Object saveOrUpdate(Employee employee) {
        JSONResult result = new JSONResult();
        try {
            employeeService.saveOrUpdate(employee);
        } catch (Exception e) {
            result.remark(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("changeState")
    @ResponseBody
    public Object changeState(Long id) {
        JSONResult result = new JSONResult();
        try {
            employeeService.changeState(id);
        } catch (Exception e) {
            result.remark(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("resetPassword")
    @RequiresPermissions(value = {"employee:resetPassword", "重置密码"}, logical = Logical.OR)
    @ResponseBody
    public Object resetPassword(Long id) {
        JSONResult result = new JSONResult();
        try {
            employeeService.resetPassword(id);
        } catch (Exception e) {
            result.remark(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("selectTeacher")
    @ResponseBody
    public Object selectTeacher() {
        return employeeService.selectTeacher();
    }
}
